package commmon.db;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Properties;

public class JdbcConnectionPool {

	private static String drivername;
	private static String databaseurl;
	private static String username;
	private static String password;
	private static int size;
	private static int maxsize;
	private static Properties prop=new Properties();
	private static int number;
	private static LinkedList<Connection> list=new LinkedList<Connection>();
	static {
//		    InputStream  in=JdbcConnectionPool.class.getResourceAsStream("/jdbc.properties");
		    InputStream in = JdbcConnectionPool.class.getClassLoader().getResourceAsStream("jdbc.properties");
			try {
				prop.load(in);
				drivername= prop.get("drivername").toString();
				databaseurl=prop.get("databaseurl").toString();
				username=prop.get("username").toString();
				password=prop.get("password").toString();
				size=Integer.parseInt(prop.getProperty("size").toString());
				maxsize=Integer.parseInt(prop.getProperty("maxsize").toString());
				Class.forName(drivername);
				for(int i=0;i<size;i++) {
					Connection con=DriverManager.getConnection(databaseurl,username,password);
					list.add(con);
				}
				System.out.println("初始化创建了"+list.size()+"个数据库连接");
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}

	}

	public static synchronized Connection  getConnection() throws SQLException {
		if(list.size()>0) {
			Connection con=list.removeFirst();
			System.out.println("数据库连接池剩余"+list.size()+"个数据库连接");
			return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[] { Connection.class }, new InvocationHandler() {
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					if(!method.getName().equals("close")) {
						return method.invoke(con, args);
					}else {
						list.add(con);
						System.out.println(con+"被释放重新加载到数据库连接池中,目前连接池个数为:"+list.size());
						return null;
					}

				}

			});
		}else {
			if(number*size>=maxsize) {
				System.out.println("数据库连接池已经达到了数据库的最大连接数，直接断开");
				return null;
			}else {

					number=number+1;

				System.out.println("数据库资源不足进行数据库连接扩容,扩容次数:"+number);
				for(int i=0;i<size;i++) {
					Connection con1=DriverManager.getConnection(databaseurl,username,password);
					list.add(con1);
				}
				System.out.println("第几"+number+"此扩容，创建了"+list.size()+"个数据库连接");
				return getConnection();
			}
		}
	}

	public static void main(String args[]) throws SQLException {
		for(int i=0;i<30;i++) {
		 Connection con=JdbcConnectionPool.getConnection();
		}
	}
}
